import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wallpaper_app/api/update.dart';
import 'package:wallpaper_app/components/button/normal_button.dart';
import 'package:wallpaper_app/components/input/normal_input.dart';
import 'package:wallpaper_app/components/windows/window_title_bar.dart';

class WallhavenApikey extends StatefulWidget {
  const WallhavenApikey({super.key});

  @override
  State<WallhavenApikey> createState() => _WallhavenApikeyState();
}

class _WallhavenApikeyState extends State<WallhavenApikey> {
  TextEditingController controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 获取本地存储的apikey
    SharedPreferences.getInstance().then((prefs) {
      final apikey = prefs.getString('wallhaven_apikey');
      if (apikey != null) {
        controller.text = apikey;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    final List<AboutItem> items = [
      AboutItem(
        title: 'wallhaven apiKey 说明',
        subtitle:
            '本应用接入了wallhaven的api，每天可以免费获取n张图片或有频率限制(详情见官网详细说明)，如果需要更多图片，请自行申请wallhaven的api key，并将其填入到上方文本框中并确认。',
      ),
      AboutItem(
        title: 'wallhaven 官网',
        subtitle: 'https://wallhaven.cc/ 点击前往官网',
        onTap: () {
          launchUrl(
            Uri.parse('https://wallhaven.cc/'),
          );
        },
      ),
      AboutItem(
        title: '注意事项',
        subtitle:
            'wallhaven国内被墙，需要全程挂载VPN才能正常使用。注册时多换几个IP地址可能才会成功。本人使用的是用日本ip才注册成功，其他ip都失败了，所以没有测试过注册是否成功。',
      ),
    ];
    return Scaffold(
      body: Column(
        children: [
          WindowTitleBar(isBack: true),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.all(8),
              child: ListView(
                children: [
                  Row(
                    spacing: 5,
                    children: [
                      Expanded(
                        child: NormalInput(
                          controller: controller,
                          suffixIcon: Icon(Icons.verified_outlined),
                          radius: 5,
                          onSubmitted: (text) async {
                            // 存储到本地
                            final prefs = await SharedPreferences.getInstance();
                            prefs.setString('wallhaven_apikey', text);
                            BotToast.showText(text: '设置成功');
                          },
                        ),
                      ),
                      SizedBox(
                        width: 150,
                        child: NormalButton(
                          title: '获取',
                          radius: 5,
                          icon: Icons.search,
                          onPressed: () async {
                            Response res = await getWallHavenApiKey();
                            if (res.statusCode == 200) {
                              controller.text = res.data['apikey'];
                              final prefs =
                                  await SharedPreferences.getInstance();
                              prefs.setString(
                                  'wallhaven_apikey', res.data['apikey']);
                              BotToast.showText(text: '获取成功');
                            } else {
                              BotToast.showText(text: '获取失败');
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                  for (var item in items)
                    Column(
                      children: [
                        Material(
                            color: theme.primaryContainer,
                            borderRadius: BorderRadius.circular(8),
                            clipBehavior: Clip.antiAlias,
                            child: ListTile(
                              title: Text(item.title),
                              // trailing: Text('vversion'),
                              subtitle: Text(item.subtitle),
                              onTap: () {
                                if (item.onTap != null) {
                                  item.onTap!();
                                }
                              },
                            )),
                        const SizedBox(height: 10),
                      ],
                    ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class AboutItem {
  final String title;
  final String subtitle;
  final Function()? onTap;
  const AboutItem({
    required this.title,
    required this.subtitle,
    this.onTap,
  });
}
